package com.stylefeng.guns.rest.modular.sms.service;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.baomidou.mybatisplus.mapper.Condition;
import com.stylefeng.guns.rest.common.base.Constans;
import com.stylefeng.guns.rest.common.persistence.dao.CountryCodeMapper;
import com.stylefeng.guns.rest.common.persistence.dao.SmsCodeMapper;
import com.stylefeng.guns.rest.common.persistence.model.CountryCode;
import com.stylefeng.guns.rest.common.persistence.model.SmsCode;
import com.stylefeng.guns.rest.common.utils.Log;
import com.stylefeng.guns.rest.modular.sms.controller.dto.SmsCodeGetRequest;
import com.stylefeng.guns.rest.modular.users.controller.dto.UserRegisterParam;
import org.apache.commons.collections.map.HashedMap;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by ASUS-PC on 2018/6/21.
 */
@Service
public class SmsCodeService {
    private static Log logger = new Log(LoggerFactory.getLogger(SmsCodeService.class));
    @Autowired
    SmsCodeMapper smsCodeMapper;
    @Autowired
    CountryCodeMapper countryCodeMapper;

    //插入验证码
    public int  inserCode(SmsCodeGetRequest request) throws ClientException {
        SmsCode smsCode = new SmsCode();
        smsCode.setMobile(request.getMobile());
        smsCode.setType(request.getType());
        smsCode.setCountryCode(request.getCode());
//        smsCode.setCreatTime(new Date());

        //阿里云api发送短信
        String smsSendCode = createCode();
        int code = getAliYunSmsCode(request,smsSendCode);
        if(code ==0){
            return code;
        }
        List<SmsCode> codeList = smsCodeMapper.selectList(Condition.create()
                .eq("mobile" , smsCode.getMobile())
                .eq("type" , smsCode.getType()));
        int state = 0;
        if (codeList.size() > 0){
            SmsCode s = codeList.get(0);
            s.setCode(smsSendCode);
            s.setUpdateTime(new Date());
            state = smsCodeMapper.update(s , Condition.create().eq("mobile" , s.getMobile()).eq("type" , s.getType()));
        }else {
            smsCode.setCode(smsSendCode);
            smsCode.setUpdateTime(new Date());
            state=smsCodeMapper.insert(smsCode);
        }
        return state > 0 ? 1:0;
    }

    //检查验证码
    public SmsCode checkSmsCode(String phone,String code,int type){
        List<SmsCode> codeList = smsCodeMapper.selectList(Condition.create()
                .eq("mobile" , phone)
                .eq("type" , type)
                .eq("code",code));
        if(codeList.size()>0){
            return codeList.get(0);
        }else
            return null;
    }

    /**
     * 创建短信验证码
     * @return
     */
    private String createCode(){
        return "" + (int)((Math.random()*9+1)*1000);
    }

    private int getAliYunSmsCode(SmsCodeGetRequest smsCodeGetRequest,String smsSendCode) throws ClientException {
        int state;
        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", Constans.ALIYUN_ACCESS_ID, Constans.ALIYUN_ACCESS_SCRET);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", "Dysmsapi", "dysmsapi.aliyuncs.com");
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        request.setMethod(MethodType.POST);
        //必填:待发送手机号
        if("86".equals(smsCodeGetRequest.getCode())){
            request.setPhoneNumbers(smsCodeGetRequest.getMobile());
        }else {
            request.setPhoneNumbers(smsCodeGetRequest.getCode()+smsCodeGetRequest.getMobile());
        }
        //必填:短信签名-可在短信控制台中找到
        request.setSignName(Constans.ALIYUN_SIGN);
        //必填:短信模板-可在短信控制台中找到
        if(smsCodeGetRequest.getType() ==1){//注册验证码
            if("86".equals(smsCodeGetRequest.getCode())){
                request.setTemplateCode(Constans.SMS_STUDENT_REGISTER_CODE);
            }else {
                request.setTemplateCode(Constans.SMS_STUDENT_GJ_REGISTER_CODE);
            }
            //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
            request.setTemplateParam("{\"code\":\""+smsSendCode+"\"}");
        }else {//重设密码
            if("86".equals(smsCodeGetRequest.getCode())){
                request.setTemplateCode(Constans.SMS_STUDENT_REGISTER_CODE);
            }else {
                request.setTemplateCode(Constans.SMS_STUDENT_GJ_REGISTER_CODE);
            }
            request.setTemplateParam("{\"code\":\""+smsSendCode+"\"}");
        }
        //选填-上行短信扩展码(无特殊需求用户请忽略此字段)
        //request.setSmsUpExtendCode("90997");
        //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
//        request.setOutId("yourOutId");

        //hint 此处可能会抛出异常，注意catch
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
        logger.i("---aliyun smscode is: "+sendSmsResponse.toString());
        System.out.println("---aliyun smscode is: "+sendSmsResponse.getCode()+"---"+sendSmsResponse.getMessage());
        if(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
            //请求成功
            state = 1;

        }else {
            state = 0;
        }
        return state;
    }

    //获取国家短信编码列表
    public List<CountryCode> getCountryCode(){
        return countryCodeMapper.getCountryCode();
    }

}
